import sys
import json
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QLineEdit, QListWidget, QTextEdit, QComboBox, QPushButton,
                             QLabel, QTabWidget, QCheckBox, QGroupBox, QScrollArea, QDialog,
                             QDialogButtonBox, QProgressBar)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QPalette, QColor

class DictionarySelectDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("ཚིག་མཛོད་འདེམ།")
        self.setModal(True)
        self.setFixedSize(400, 500)
        
        layout = QVBoxLayout(self)
        
        # 全选按钮
        select_all_btn = QPushButton("ཡོངས་འདེམ།")
        select_all_btn.clicked.connect(self.select_all_dicts)
        layout.addWidget(select_all_btn)
        
        # 词典复选框区域
        scroll_area = QScrollArea()
        scroll_widget = QWidget()
        self.dict_checkbox_layout = QVBoxLayout(scroll_widget)
        scroll_area.setWidget(scroll_widget)
        scroll_area.setWidgetResizable(True)
        layout.addWidget(scroll_area)
        
        # 确定按钮
        button_box = QDialogButtonBox(QDialogButtonBox.Ok)
        button_box.accepted.connect(self.accept)
        layout.addWidget(button_box)
        
        self.dict_checkboxes = {}
    
    def select_all_dicts(self):
        """全选所有词典"""
        for checkbox in self.dict_checkboxes.values():
            checkbox.setChecked(True)
    
    def setup_dicts(self, dictionaries):
        """设置词典复选框"""
        for dict_name in dictionaries:
            checkbox = QCheckBox(dict_name)
            checkbox.setChecked(True)
            self.dict_checkboxes[dict_name] = checkbox
            self.dict_checkbox_layout.addWidget(checkbox)
        self.dict_checkbox_layout.addStretch()
    
    def get_selected_dicts(self):
        """获取选中的词典列表"""
        return [dict_name for dict_name, checkbox in self.dict_checkboxes.items() 
                if checkbox.isChecked()]

class LoadingDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("འཚོལ་བཞིན་པ...")
        self.setModal(True)
        self.setFixedSize(300, 150)
        self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint)
        self.setStyleSheet("""
            QDialog {
                background-color: white;
                border: 2px solid #1E90FF;
                border-radius: 10px;
            }
        """)
        
        layout = QVBoxLayout(self)
        layout.setAlignment(Qt.AlignCenter)
        
        # 加载动画标签
        self.loading_label = QLabel("འཚོལ་བཤེར་བྱེད་བཞིན་པ།...")
        self.loading_label.setAlignment(Qt.AlignCenter)
        self.loading_label.setStyleSheet("font-size: 16px; color: #1E90FF;")
        layout.addWidget(self.loading_label)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 0)  # 无限循环进度条
        self.progress_bar.setTextVisible(False)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                border: 1px solid #ccc;
                border-radius: 5px;
                background-color: #f0f0f0;
                height: 10px;
            }
            QProgressBar::chunk {
                background-color: #1E90FF;
                border-radius: 5px;
            }
        """)
        layout.addWidget(self.progress_bar)

    def set_message(self, message):
        """设置加载消息"""
        self.loading_label.setText(message)

class TibetanDictionaryGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.dictionaries = {}
        self.current_dict = None
        self.selected_dicts = []
        self.loading_dialog = None  # loading对话框引用
        self.initUI()
        self.scan_dictionary_files()

    def initUI(self):
        # 设置主窗口
        self.setWindowTitle('བོད་ཡིག་ཚིག་མཛོད་ཀུན་བཏུས།')
        self.setGeometry(100, 100, 1400, 900)
        
        # 设置网易词典风格的主题
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f5f5f5;
            }
            QGroupBox {
                font-weight: bold;
                border: 2px solid #1E90FF;
                border-radius: 8px;
                margin-top: 1ex;
                padding-top: 10px;
                background-color: white;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 5px;
                color: #1E90FF;
            }
            QLineEdit {
                border: 2px solid #1E90FF;
                border-radius: 6px;
                padding: 8px;
                font-size: 18px;
                background-color: white;
            }
            QListWidget {
                border: 1px solid #ccc;
                border-radius: 6px;
                background-color: white;
                alternate-background-color: #f8f8f8;
            }
            QListWidget::item {
                padding: 8px;
                border-bottom: 1px solid #eee;
            }
            QListWidget::item:selected {
                background-color: #1E90FF;
                color: white;
            }
            QTextEdit {
                border: 1px solid #ccc;
                border-radius: 6px;
                padding: 10px;
                background-color: white;
                font-size: 18px;  
            }
            QPushButton {
                background-color: #1E90FF;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 8px 16px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #0078D7;
            }
            QPushButton:pressed {
                background-color: #005A9E;
            }
            QComboBox {
                border: 2px solid #1E90FF;
                border-radius: 6px;
                padding: 6px;
                background-color: white;
            }
        """)

        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 左侧面板 - 搜索
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)
        left_panel.setFixedWidth(400)
        
        # 词典选择按钮
        dict_btn = QPushButton("ཚིག་མཛོད་འདེམ།")
        dict_btn.clicked.connect(self.show_dict_select_dialog)
        left_layout.addWidget(dict_btn)
        
        # 搜索组
        search_group = QGroupBox("འཚོལ་བཤེར།")
        search_layout = QVBoxLayout(search_group)
        
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("འཚོལ་བྱའི་མིག་ཚིག་གཏག་རོགས...")
        self.search_input.returnPressed.connect(self.search_words)
        search_layout.addWidget(self.search_input)
        
        search_btn = QPushButton("འཚོལ་བཤེར།")
        search_btn.clicked.connect(self.search_words)
        search_layout.addWidget(search_btn)
        
        left_layout.addWidget(search_group)
        
        # 结果列表组
        results_group = QGroupBox("ཚིག་འབྲེལ།")
        results_layout = QVBoxLayout(results_group)
        
        self.results_list = QListWidget()
        self.results_list.itemClicked.connect(self.show_definition)
        results_layout.addWidget(self.results_list)
        
        left_layout.addWidget(results_group)
        
        # 右侧面板 - 定义显示
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)
        
        # 直接显示所有词典释义的文本区域
        self.definition_display = QTextEdit()
        self.definition_display.setReadOnly(True)
        self.definition_display.setFont(QFont("Microsoft Himalaya", 25))  # 放大5倍字号
        right_layout.addWidget(self.definition_display)
        
        main_layout.addWidget(left_panel)
        main_layout.addWidget(right_panel)

    def show_dict_select_dialog(self):
        """显示词典选择对话框"""
        dialog = DictionarySelectDialog(self)
        dialog.setup_dicts(self.dictionaries.keys())
        if dialog.exec_() == QDialog.Accepted:
            self.selected_dicts = dialog.get_selected_dicts()

    def show_loading(self, message="འཚོལ་བཤེར་བྱེད་བཞིན་པ།..."):
        """显示loading弹窗"""
        if self.loading_dialog is None:
            self.loading_dialog = LoadingDialog(self)
        self.loading_dialog.set_message(message)
        self.loading_dialog.show()
        # 强制处理事件，确保弹窗立即显示
        QApplication.processEvents()

    def hide_loading(self):
        """隐藏loading弹窗"""
        if self.loading_dialog:
            self.loading_dialog.close()
            self.loading_dialog = None

    def scan_dictionary_files(self):
        """扫描tibetan_dicts目录下的JSON词典文件"""
        dicts_dir = os.path.join(os.path.dirname(__file__), 'tibetan_dicts')
        if not os.path.exists(dicts_dir):
            print(f"词典目录不存在: {dicts_dir}")
            return
        
        for filename in os.listdir(dicts_dir):
            if filename.endswith('.json'):
                dict_name = filename[:-5]  # 移除.json后缀
                filepath = os.path.join(dicts_dir, filename)
                try:
                    with open(filepath, 'r', encoding='utf-8') as f:
                        self.dictionaries[dict_name] = json.load(f)
                    print(f"已加载词典: {dict_name}")
                except Exception as e:
                    print(f"加载词典 {dict_name} 时出错: {e}")
        
        # 默认选择所有词典
        self.selected_dicts = list(self.dictionaries.keys())

    def search_words(self):
        """在所有选中的词典中搜索词汇"""
        query = self.search_input.text().strip()
        if not query:
            return
        
        # 显示loading弹窗
        self.show_loading("འཚོལ་བཤེར་བྱེད་བཞིན་པ།...")
        
        try:
            # 清空之前的结果
            self.results_list.clear()
            self.definition_display.clear()
            
            if not self.selected_dicts:
                self.results_list.addItem("ཚིག་མཛོད་འདེམ་རོགས།")
                return
            
            all_results = {}
            
            # 在每个选中的词典中搜索
            for dict_name in self.selected_dicts:
                if dict_name in self.dictionaries:
                    dictionary = self.dictionaries[dict_name]
                    results = self.search_in_dictionary(dictionary, query)
                    if results:
                        all_results[dict_name] = results
            
            # 显示合并的搜索结果
            combined_results = set()
            for dict_results in all_results.values():
                combined_results.update(dict_results.keys())
            
            # 按匹配质量排序：精确匹配 > 包含匹配 > 前缀匹配
            exact_matches = []
            contains_matches = []
            prefix_matches = []
            reverse_matches = []
            
            for word in combined_results:
                if word == query:
                    exact_matches.append(word)
                elif query in word:
                    contains_matches.append(word)
                elif word.startswith(query):
                    prefix_matches.append(word)
                else:
                    # 检查是否在定义中包含查询词
                    for dict_name in self.selected_dicts:
                        if dict_name in self.dictionaries and word in self.dictionaries[dict_name]:
                            definition = self.dictionaries[dict_name][word]
                            if isinstance(definition, str) and query in definition:
                                reverse_matches.append(word)
                                break
            
            # 添加结果到列表
            if exact_matches:
                self.results_list.addItem("=== ཚིག་མཐུན། ===")
                for word in sorted(exact_matches):
                    self.results_list.addItem(word)
            
            if contains_matches:
                self.results_list.addItem("=== ཚིག་འདུ། ===")
                for word in sorted(contains_matches):
                    self.results_list.addItem(word)
            
            if prefix_matches:
                self.results_list.addItem("=== སྔོན་མ་མཐུན་པ། ===")
                for word in sorted(prefix_matches):
                    self.results_list.addItem(word)
            
            if reverse_matches:
                self.results_list.addItem("=== བར་མ་མཐུན་པ། ===")
                for word in sorted(reverse_matches):
                    self.results_list.addItem(word)
            
            # 直接显示所有词典的搜索结果
            self.display_all_definitions(all_results, query)
            
        finally:
            # 隐藏loading弹窗
            self.hide_loading()

    def display_all_definitions(self, all_results, query):
        """直接显示所有词典的释义"""
        content = f"<div style='font-size: 25px;'>"  # 放大5倍字号
        
        for dict_name, results in all_results.items():
            if results:
                content += f"<h2 style='color: #1E90FF;'>{dict_name}</h2>"
                for word, definition in results.items():
                    highlighted_def = definition
                    if isinstance(definition, str):
                        # 高亮显示查询词
                        highlighted_def = definition.replace(query, f'<span style="background-color: #FFFF00">{query}</span>')
                    content += f"<p><b style='font-size: 28px;'>{word}</b><br>{highlighted_def}</p><hr>"
        
        if not all_results:
            content += "<p style='color: red; font-size: 30px;'>未找到相关结果</p>"
        
        content += "</div>"
        self.definition_display.setHtml(content)

    def search_in_dictionary(self, dictionary, query):
        """在单个词典中搜索词汇"""
        results = {}
        
        # 精确匹配
        if query in dictionary:
            results[query] = dictionary[query]
        
        # 包含匹配
        for word, definition in dictionary.items():
            if query in word and word != query:
                results[word] = definition
        
        # 前缀匹配
        for word, definition in dictionary.items():
            if word.startswith(query) and word != query:
                results[word] = definition
        
        return results

    def show_definition(self, item):
        """显示选中词汇的定义"""
        word = item.text()
        if word.startswith("==="):  # 跳过分隔符
            return
        
        # 在所有选中的词典中查找该词汇
        definitions = {}
        for dict_name in self.selected_dicts:
            if dict_name in self.dictionaries:
                dictionary = self.dictionaries[dict_name]
                if word in dictionary:
                    definitions[dict_name] = dictionary[word]
        
        if not definitions:
            return
        
        # 直接显示所有词典的定义
        content = f"<div style='font-size: 25px;'>"
        content += f"<h1 style='color: #1E90FF;'>{word}</h1>"
        
        for dict_name, definition in definitions.items():
            content += f"<h2 style='color: #0078D7;'>{dict_name}</h2>"
            if isinstance(definition, str):
                content += f"<p>{definition}</p>"
            else:
                content += f"<p>{str(definition)}</p>"
            content += "<hr>"
        
        content += "</div>"
        self.definition_display.setHtml(content)

def main():
    app = QApplication(sys.argv)
    
    # 设置应用程序字体
    font = QFont("Microsoft Himalaya", 16)
    app.setFont(font)
    
    window = TibetanDictionaryGUI()
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()